package com.droidexchange.activity;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import net.sf.stackwrap4j.entities.Tag;
import net.sf.stackwrap4j.json.JSONException;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.MultiAutoCompleteTextView;
import com.droidexchange.R;
import com.droidexchange.util.Util;

public class TagsActivity extends Activity
{
	MultiAutoCompleteTextView	macTxtView;
	String[]					validTags	= null;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		String tags = getIntent().getStringExtra("tags");
		if (tags == null)
			finish();

		Util.log("Tags requested: " + tags);
		setContentView(R.layout.tags_layout);
		macTxtView = (MultiAutoCompleteTextView) findViewById(R.id.mactv);
		macTxtView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
		macTxtView.setText(tags);

		Util.waitForDebugger();
		listTags();
	}
	
	private void listTags()
	{
		try
		{
			List<Tag> validTagsList = Util.sw.listTags();
			validTags = new String[validTagsList.size()];
			for(int i = 0; i < validTagsList.size(); i++)
			{
				Tag tag = validTagsList.get(i);
				validTags[i] = tag.getName();
			}

			//validTags = Util.split(tags, ",");
			macTxtView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, validTags));
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
	}

	public void clickHandler(View v)
	{
		if (v instanceof Button)
		{
			String btnName = (String) ((Button) v).getText();
			if (btnName.equals(getResources().getString(R.string.filter_cancel)))
			{
				Intent intent = new Intent();
				setResult(RESULT_CANCELED, intent);
				finish();
			}
			else if (((Button) v).getText().equals(getResources().getString(R.string.filter_done)))
			{
				Intent intent = new Intent();
				intent.putExtra("tags", checkValidTags(macTxtView.getText().toString()));
				setResult(RESULT_OK, intent);
				finish();
			}
		}
	}

	private String checkValidTags(String input)
	{
		if (input == null || input.length() <= 0)
			return null;
		
		List<String> validTagsArray = Arrays.asList(validTags);
		String[] items = Util.split(input, ",");
		String validItems = "";
		for(int i = 0; i < items.length; i++)
		{
			if (validTagsArray.contains(items[i]))
				validItems += items[i] + ",";
		}
		
		if (validItems.length() <= 0)
			return null;
		
		validItems = validItems.substring(0, validItems.lastIndexOf(','));
		
		return validItems; 
	}
}
